<template>
  <canvas :id="'container'+index"/>
</template>

<script>
  import F2 from '@antv/f2';

  export default {
    name: 'index',
    data() {
      return {};
    },
    props: {
      index: {
        type: Number,
        default: 0
      },
      data: {
        type: Object,
        default: () => ({})
      }
    },
    mounted() {
      this.init();
    },
    methods: {
      init() {
        const { fields } = this.data;
        let { data } = this.data;
        if (!data) {
          return;
        }

        const [fieldX, fieldY] = fields;
        const chart = new F2.Chart({
          id: 'container' + this.index,
          pixelRatio: window.devicePixelRatio
        });

        data = data.reverse();
        chart.source(data, {
          [fieldY]: {
            tickCount: 5
          }
        });
        chart.coord({
          transposed: true
        });

        chart.tooltip(false);
        chart.interval().position(`${fieldX}*${fieldY}`);
        chart.render();
        const offset = 15;
        const canvas = chart.get('canvas');
        const group = canvas.addGroup();
        data.forEach(function (obj) {
          const point = chart.getPosition(obj);
          group.addShape('text', {
            attrs: {
              x: point.x + offset,
              y: point.y + 8,
              text: obj[fieldY] + '亿',
              textAlign: 'center',
              textBaseline: 'bottom',
              fill: '#808080'
            }
          });
        });
      }
    }
  };
</script>

<style scoped lang="less">
  canvas {
    width: 100%;
    background: #fff;
    padding: 12px;
    height: 300px;
  }
</style>
